package com.kefu.call.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.kefu.basic.util.RedisLockUtil;
import com.kefu.call.mapper.*;
import com.kefu.call.model.*;
import com.kefu.call.vo.CallHangUpVo;
import com.kefu.call.vo.CallHangupPushVo;
import com.kefu.call.vo.GatewayByRegionVo;
import com.kefu.common.exception.BusinessException;
import com.kefu.common.util.DateUtils;
import com.kefu.common.util.JacksonUtil;
import com.kefu.common.util.StreamUtil;
import com.kefu.crm.mapper.CrmCustomerMapper;
import com.kefu.crm.model.CrmCustomer;
import com.kefu.crm.utils.PhoneDat;
import com.kefu.framework.config.KefuProperties;
import com.kefu.sys.mapper.SysGroupMapper;
import com.kefu.sys.mapper.SysTenantMapper;
import com.kefu.sys.mapper.SysUserMapper;
import com.kefu.sys.model.SysGroup;
import com.kefu.sys.model.SysTenant;
import com.kefu.sys.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CallNotifyService {
    @Resource
    private CallMakeCallMapper callMakeCallMapper;
    @Resource
    private CallCompanyMapper callCompanyMapper;
    @Resource
    private CallStartMapper callStartMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private CrmCustomerMapper crmCustomerMapper;
    @Resource
    private RecordLogMapper recordLogMapper;
    @Resource
    private AgentHoldMapper agentHoldMapper;
    @Resource
    private AgentServiceLevelMapper agentServiceLevelMapper;
    @Resource
    private SysGroupMapper sysGroupMapper;
    @Resource
    private CallIvrTrailMapper callIvrTrailMapper;
    @Autowired
    private RedisLockUtil redisLockUtil;
    @Resource
    private CallVoiceMailMapper callVoiceMailMapper;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    RedisTemplate<String,Map<String,String>> redisTemplate1;
    @Resource
    private SysTenantMapper sysTenantMapper;
    @Autowired
    private KefuProperties kefuProperties;
    @Autowired
    private PhoneDat phoneDat;
    @Resource
    private CallGatewayMapper callGatewayMapper;
    @Resource
    private CallTransferMapper callTransferMapper;

    public void hangUp(CallHangUpVo vo) {
        //防止重复调用
        if(redisLockUtil.beLock("callHangUp:"+vo.getId()+":"+vo.getCallType())){
            return;
        }
        //呼入
        if (vo.getCallType() == 1) {
        	callIn(vo);
        }
        //呼出
        else if (vo.getCallType() == 2) {
        	callOut(vo);
        }
    }


    void callOut(CallHangUpVo vo) {
        CallMakeCall call = callMakeCallMapper.selectOne(Wrappers.lambdaQuery(CallMakeCall.class)
                .eq(CallMakeCall::getCallId, vo.getId()).orderByDesc(CallMakeCall::getRingTime).last("limit 1"));
        if (call == null || StrUtil.isBlank(call.getCallId())) {
            return;
        }
        CallMakeCall callMakeCall = new CallMakeCall();
        log.info("hangUp_callOut_start:{}", call);
        //坐席姓名
        if (StrUtil.isNotBlank(call.getAgentId())) {
            SysUser sysUser = sysUserMapper.selectById(call.getAgentId());
            if (sysUser != null) {
                callMakeCall.setAgentName(sysUser.getUserName());
                callMakeCall.setAgentEmail(sysUser.getUserEmail());
                callMakeCall.setAgentJobno(sysUser.getUserJobno());
            }
        }
        //客户信息
        if (StrUtil.isNotBlank(call.getCalleeNumber())) {
            CrmCustomer crmCustomer;
            //号码归属地
            callMakeCall.setPhoneCarrier(phoneDat.getCity(call.getCalleeNumber()));
            if(StrUtil.isNotBlank(call.getCustomerId())){
                crmCustomer = crmCustomerMapper.selectById(call.getCustomerId());
            }else {
                crmCustomer = crmCustomerMapper.selectOne(Wrappers.lambdaQuery(CrmCustomer.class).eq(CrmCustomer::getPhone, call.getCalleeNumber())
                        .eq(CrmCustomer::getTenantId,call.getCompany()).last("limit 1"));
            }
            if(crmCustomer!=null) {
                callMakeCall.setCustomerId(crmCustomer.getCustomerId());
                callMakeCall.setCustomerName(crmCustomer.getName());
                callMakeCall.setCustomerCompanyId(crmCustomer.getEnterpriseId());
                callMakeCall.setCustomerCompanyName(crmCustomer.getEnterpriseName());
            }
        }
        //接听状态
        if (StrUtil.isNotBlank(call.getCalleeAnswerTime())) {
            callMakeCall.setAnswerStatus("1");
            callMakeCall.setNumberStatus("NORMAL");
        }
        //通话时长避免负数情况
        if(call.getTalkTime()!=null && call.getTalkTime()<0){
            callMakeCall.setTalkTime(0);
        }
        //振铃时长
        if (StrUtil.isNotBlank(call.getCalleeRingTime()) && StrUtil.isNotBlank(call.getCalleeAnswerTime())) {
            long startTime = DateUtils.parseToTime(call.getCalleeRingTime());
            long endTime = DateUtils.parseToTime(call.getCalleeAnswerTime());
            if (endTime >= startTime) {
                callMakeCall.setRingDurationTime(Convert.toInt((endTime - startTime) / 1000));
            }
        }
        //总时长
        if (StrUtil.isAllNotBlank(call.getRingTime(), call.getCallHangupTime())) {
            long startTime = DateUtils.parseToTime(call.getRingTime());
            long endTime = DateUtils.parseToTime(call.getCallHangupTime());
            if (endTime >= startTime) {
                callMakeCall.setTotalTime(Convert.toInt((endTime - startTime) / 1000));
            }
        }
        // 保持时长
        List<AgentHold> agentHoldList = agentHoldMapper.selectList(Wrappers.lambdaQuery(AgentHold.class).eq(AgentHold::getUuid, call.getCallId()));
        if (CollUtil.isNotEmpty(agentHoldList)) {
            int holdNum = 0;
            int holdTime = 0;
            for (AgentHold agentHold : agentHoldList) {
                holdNum += 1;
                String createEndTime = agentHold.getCreateEndTime();
                String createStartTime = agentHold.getCreateStartTime();
                if (StrUtil.isNotBlank(createEndTime) && StrUtil.isNotBlank(createStartTime)) {
                    long startTime = DateUtils.parseToTime(createStartTime);
                    long endTime = DateUtils.parseToTime(createEndTime);
                    if (endTime >= startTime) {
                        holdTime += (endTime - startTime) / 1000;
                    }
                }
            }
            callMakeCall.setHoldNum(holdNum);
            callMakeCall.setHoldTime(holdTime);
        }
        //录音
        List<RecordLog> recordLogList = recordLogMapper.selectList(Wrappers.lambdaQuery(RecordLog.class)
                .orderByDesc(RecordLog::getStartTime).eq(RecordLog::getUuid, call.getCallId()));
        if (CollUtil.isNotEmpty(recordLogList)) {
            callMakeCall.setRecordUrl(kefuProperties.getDomain() + recordLogList.get(0).getFile());
        }
        //满意度评价
        AgentServiceLevel agentServiceLevel = agentServiceLevelMapper.selectOne(Wrappers.lambdaQuery(AgentServiceLevel.class)
                .eq(AgentServiceLevel::getUuid, call.getCallId()).last("limit 1"));
        if (agentServiceLevel!=null) {
            if(StrUtil.isBlank(call.getLevelVal())){
                callMakeCall.setLevelVal(agentServiceLevel.getNLevel());
            }
            if(StrUtil.isBlank(call.getLevelName())){
                callMakeCall.setLevelName(agentServiceLevel.getNLevelName());
            }
        }
        //更新数据入库
        callMakeCall.setUuid(call.getUuid());
        callMakeCall.setUpdateTime(System.currentTimeMillis());
        callMakeCallMapper.updateById(callMakeCall);
        //移除MRCPCALL中的消息移动到MRCPCALL_END
        Map<String,String> map = Maps.newHashMap();
        map.put("callid", vo.getId());
        map.put("company", call.getCompany());
        redisTemplate1.opsForList().remove("MRCPCALL", 1, map);
        redisTemplate1.opsForList().leftPush("MRCPCALL_END", map);
        //消息推送
        pushData(vo.getId(),vo.getCallType(),call.getCompany());
        log.info("hangUp_callOut_end:{}", callMakeCall);
    }

    void callIn(CallHangUpVo vo) {
        CallStart call  = callStartMapper.selectOne(
                Wrappers.lambdaQuery(CallStart.class)
                        .eq(CallStart::getCallId, vo.getId())
                        .eq(StrUtil.isNotBlank(vo.getTransferId()), CallStart::getTransferId, vo.getTransferId())
                        .orderByAsc(CallStart::getIvrStartTime).last("limit 1"));
        if (call == null || StrUtil.isBlank(call.getCallId())) {
            return;
        }
        log.info("呼入回调 : {}", JacksonUtil.toString(call));

        CallStart callStart = new CallStart();
        if (StrUtil.isNotBlank(call.getAgentId())) {
            SysUser sysUser = sysUserMapper.selectById(call.getAgentId());
            if (sysUser != null) {
                callStart.setAgentName(sysUser.getUserName());
                callStart.setAgentEmail(sysUser.getUserEmail());
                callStart.setAgentJobno(sysUser.getUserJobno());
            }
        }
        log.info("呼入回调, 补齐坐席信息 : {}", JacksonUtil.toString(call));
        if (StrUtil.isNotBlank(call.getGroupId())) {
            SysGroup sysGroup = sysGroupMapper.selectByPrimaryKey(call.getGroupId());
            if (sysGroup != null) {
                callStart.setGroupName(sysGroup.getGroupName());
            }
        }
        log.info("呼入回调, 补齐技能组信息 : {}", JacksonUtil.toString(call));
        if (StrUtil.isNotBlank(call.getCallerNumber())) {
            CrmCustomer crmCustomer;
            String customerPhone = call.getCallerNumber();
            callStart.setPhoneCarrier(phoneDat.getCity(customerPhone));
            callStart.setCallingCity(phoneDat.getSingletonCity(customerPhone));
            callStart.setCallingProvince(phoneDat.getProvince(customerPhone));
            if(StrUtil.isNotBlank(call.getCustomerId())){
                crmCustomer = crmCustomerMapper.selectById(call.getCustomerId());
            }else {
                crmCustomer = crmCustomerMapper.selectOne(Wrappers.lambdaQuery(CrmCustomer.class).eq(CrmCustomer::getPhone, customerPhone)
                        .eq(CrmCustomer::getTenantId,call.getCompany()).last("limit 1"));
            }
            if(crmCustomer!=null) {
                callStart.setCustomerId(crmCustomer.getCustomerId());
                callStart.setCustomerName(crmCustomer.getName());
                callStart.setCustomerCompanyId(crmCustomer.getEnterpriseId());
                callStart.setCustomerCompanyName(crmCustomer.getEnterpriseName());
            }
            // 是否一次性解决
            callStart.setIsOnceSolve(1);
            List<CallStart> list = callStartMapper.selectList(Wrappers.lambdaQuery(CallStart.class)
                    .eq(CallStart::getCallerNumber, call.getCallerNumber())
                    .gt(CallStart::getIvrStartTime, DateUtils.dateTimeFormat(DateUtil.beginOfDay(new Date()).getTime()))
                    .lt(CallStart::getIvrStartTime, DateUtils.dateTimeFormat(DateUtil.endOfDay(new Date()).getTime()))
                    .ne(CallStart::getCallId, call.getCallId())
            );
            if (CollUtil.isNotEmpty(list)) {
                callStart.setIsOnceSolve(0);
                for (CallStart i : list) {
                    i.setIsOnceSolve(0);
                    callStartMapper.updateById(i);
                    log.info("客户今日来电次数超过1次，上次的来电是: {}", JacksonUtil.toString(i));
                }
            }
        }
        log.info("呼入回调, 补齐客户信息 : {}", JacksonUtil.toString(call));

        if (StrUtil.isNotBlank(call.getAgentAnsweredTime())) {
            callStart.setAnswerStatus("1");
        } else {
            callStart.setAnswerStatus("0");
            callStart.setCallFailType(StrUtil.isBlank(call.getGroupId()) ? 0 :
                    StrUtil.isBlank(call.getAgentCalledTime()) ? 5 : 10);
        }

        log.info("呼入回调, 补齐接听状态信息 : {}", JacksonUtil.toString(call));
        if (StrUtil.isBlank(call.getQueueStartTime())) {
            callStart.setQueueStatus(0);
            callStart.setQueueDurationTime(0);
        } else {
            Long endTime = null;
            long startTime = DateUtils.parseToTime(call.getQueueStartTime());
            if (StrUtil.isNotBlank(call.getQueueEndTime())) {
                endTime = DateUtils.parseToTime(call.getQueueEndTime());
            } else {
                if (StrUtil.isNotBlank(call.getCallEndTime())) {
                    endTime = DateUtils.parseToTime(call.getCallEndTime());
                }
            }
            if (Objects.isNull(endTime)) {
                log.info("呼入回调:{}, 无法计算坐席排队时长,{},{}",
                        callStart.getOid(), call.getQueueEndTime(), call.getCallEndTime());
            }
            if (endTime >= startTime) {
                Integer queueDurationTime = Convert.toInt((endTime - startTime) / 1000);
                callStart.setQueueDurationTime(queueDurationTime);
                callStart.setQueueStatus(queueDurationTime == 0 ? 0 : 1);
            }
        }
        log.info("呼入回调, 补齐排队时长，排队状态信息 : {}", JacksonUtil.toString(call));

        //坐席振铃时长
        if (StrUtil.isNotBlank(call.getAgentCalledTime())) {
            Long endTime = null;
            long startTime = DateUtils.parseToTime(call.getAgentCalledTime());
            if (StrUtil.isNotBlank(call.getAgentAnsweredTime())) {
                endTime = DateUtils.parseToTime(call.getAgentAnsweredTime());
            } else {
                if (StrUtil.isNotBlank(call.getCallEndTime())) {
                    endTime = DateUtils.parseToTime(call.getCallEndTime());
                }
            }
            if (Objects.isNull(endTime)) {
                log.info("呼入回调:{}, 无法计算坐席振铃时长,{},{}",
                        callStart.getOid(), call.getAgentAnsweredTime(), call.getCallEndTime());
            }
            if (endTime >= startTime) {
                callStart.setCalleeRingDurationTime(Convert.toInt((endTime - startTime) / 1000));
            }
        }
        log.info("呼入回调, 补齐坐席振铃时长信息 : {}", JacksonUtil.toString(call));

        //总时长
        if (StrUtil.isAllNotBlank(call.getIvrStartTime(), call.getHangupCauseTime())) {
            long startTime = DateUtils.parseToTime(call.getIvrStartTime());
            long endTime = DateUtils.parseToTime(call.getHangupCauseTime());
            if (endTime >= startTime) {
                callStart.setTotalTime(Convert.toInt((endTime - startTime) / 1000));
            }
        }
        log.info("呼入回调, 补齐总时长信息 : {}", JacksonUtil.toString(call));

        //通话时长
        if (StrUtil.isNotBlank(call.getAgentAnsweredTime()) && StrUtil.isNotBlank(call.getCallEndTime())) {
            long startTime = DateUtils.parseToTime(call.getAgentAnsweredTime());
            long endTime = DateUtils.parseToTime(call.getCallEndTime());
            if (endTime >= startTime) {
                callStart.setTalkTime(Convert.toInt((endTime - startTime) / 1000));
            }
        }
        log.info("呼入回调, 补齐通话时长信息 : {}", JacksonUtil.toString(call));

        // 保持时长
        List<AgentHold> agentHoldList = agentHoldMapper.selectList(Wrappers.lambdaQuery(AgentHold.class).eq(AgentHold::getUuid, call.getCallId()));
        if (CollUtil.isNotEmpty(agentHoldList)) {
            int holdNum = 0;
            int holdTime = 0;
            for (AgentHold agentHold : agentHoldList) {
                holdNum += 1;
                String createEndTime = agentHold.getCreateEndTime();
                String createStartTime = agentHold.getCreateStartTime();
                if (StrUtil.isNotBlank(createEndTime) && StrUtil.isNotBlank(createStartTime)) {
                    long startTime = DateUtils.parseToTime(createStartTime);
                    long endTime = DateUtils.parseToTime(createEndTime);
                    if (endTime >= startTime) {
                        holdTime += (endTime - startTime) / 1000;
                    }
                }
            }
            callStart.setHoldNum(holdNum);
            callStart.setHoldTime(holdTime);
        }
        log.info("呼入回调, 补齐保持信息 : {}", JacksonUtil.toString(call));

        //录音
        List<RecordLog> recordLogList = recordLogMapper.selectList(Wrappers.lambdaQuery(RecordLog.class)
                .orderByDesc(RecordLog::getStartTime).eq(RecordLog::getUuid, call.getCallId()));
        if (CollUtil.isNotEmpty(recordLogList)) {
            callStart.setRecordUrl(kefuProperties.getDomain() + recordLogList.get(0).getFile());
        }

        //ivr轨迹
        List<CallIvrTrail> callIvrTrailList = callIvrTrailMapper.selectList(Wrappers.lambdaQuery(CallIvrTrail.class)
                .eq(CallIvrTrail::getCallId, call.getCallId()).orderByAsc(CallIvrTrail::getCreateTime));
        if (CollUtil.isNotEmpty(callIvrTrailList)) {
            callStart.setIvrTrial(StreamUtil.stream(callIvrTrailList).map(CallIvrTrail::getNodeType).collect(Collectors.joining(",")));
        }

        //满意度评价
        AgentServiceLevel agentServiceLevel = agentServiceLevelMapper.selectOne(Wrappers.lambdaQuery(AgentServiceLevel.class)
                .eq(AgentServiceLevel::getUuid, call.getCallId()).last("limit 1"));
        if (agentServiceLevel!=null) {
            if(StrUtil.isBlank(call.getLevelVal())){
                callStart.setLevelVal(agentServiceLevel.getNLevel());
            }
            if(StrUtil.isBlank(call.getLevelName())){
                callStart.setLevelName(agentServiceLevel.getNLevelName());
            }
        }

        //更新呼叫留言
        CallVoiceMail voiceMail = callVoiceMailMapper.selectById(call.getCallId());
        if(voiceMail != null){
            LambdaUpdateWrapper<CallVoiceMail> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.set(CallVoiceMail::getTenantId, call.getCompany());
            updateWrapper.set(CallVoiceMail::getCustomerPhone, voiceMail.getAni());
            updateWrapper.eq(CallVoiceMail::getUuid, call.getCallId());
            callVoiceMailMapper.update(null, updateWrapper);
        }

        //更新数据入库
        callStart.setAutoTask("0");
        callStart.setOid(call.getOid());
        callStart.setUpdateTime(System.currentTimeMillis());
        callStartMapper.updateById(callStart);

        //处理转接数据
        if("1".equals(call.getIstransfer())){
            handleTransfer(vo);
        }
        //移除MRCPCALL中的消息移动到MRCPCALL_END
        Map<String,String> map = Maps.newHashMap();
        map.put("callid", vo.getId());
        map.put("company", call.getCompany());
        redisTemplate1.opsForList().remove("MRCPCALL", 1, map);
        redisTemplate1.opsForList().leftPush("MRCPCALL_END", map);
        //消息推送
        pushData(vo.getId(),vo.getCallType(),call.getCompany());
        log.info("hangUp_callIn_end:{}", callStart);
    }

    //消息推送
    public void pushData(String callId,int callType,String tenantId){
        SysTenant sysTenant = sysTenantMapper.selectById(tenantId);
        if (sysTenant!=null && StrUtil.isNotBlank(sysTenant.getPushCallHangup())){
            ThreadUtil.execute(() -> {
                CallHangupPushVo pushVo = null;
                try {
                    //呼入
                    if (callType==1) {
                        CallStart callDb = callStartMapper.selectOne(Wrappers.lambdaQuery(CallStart.class)
                                .eq(CallStart::getCallId, callId).orderByDesc(CallStart::getIvrStartTime).last("limit 1"));
                        pushVo = BeanUtil.toBean(callDb, CallHangupPushVo.class);
                        pushVo.setCallType(1);
                        pushVo.setStartTime(callDb.getIvrStartTime());
                        pushVo.setAnswerTime(callDb.getAgentAnsweredTime());
                        pushVo.setHangUpTime(callDb.getHangupCauseTime());
                    }
                    //外呼
                    else if (callType==2) {
                        CallMakeCall callDb = callMakeCallMapper.selectOne(Wrappers.lambdaQuery(CallMakeCall.class)
                                .eq(CallMakeCall::getCallId, callId).orderByDesc(CallMakeCall::getRingTime).last("limit 1"));
                        pushVo = BeanUtil.toBean(callDb, CallHangupPushVo.class);
                        pushVo.setCallType(2);
                        pushVo.setStartTime(callDb.getRingTime());
                        pushVo.setHangUpTime(callDb.getCallHangupTime());
                    }
                    if(pushVo==null){
                        return;
                    }
                    if (StrUtil.isNotBlank(pushVo.getCustomerId())) {
                        CrmCustomer crmCustomer = crmCustomerMapper.selectById(pushVo.getCustomerId());
                        if (crmCustomer != null) {
                            pushVo.setCustomerPid(crmCustomer.getPid());
                        }
                    }
                    String url = sysTenant.getPushCallHangup();
                    String nonce = String.valueOf(new Random().nextInt(9999));
                    String time = String.valueOf(System.currentTimeMillis());
                    String sign = SecureUtil.sha1(sysTenant.getAppSecret() + nonce + time);
                    String json = JacksonUtil.toString(pushVo);
                    String result = HttpUtil.createPost(url)
                            .header("tenant", sysTenant.getTenantId())
                            .header("nonce", nonce)
                            .header("time", time)
                            .header("sign",sign)
                            .header("type","call_hang_up")
                            .body(json).execute().body();
                    log.info("push_call_hang_up:{},{},{},{},{},{}",url,nonce,time,sign,json,result);
                    if (StrUtil.isNotBlank(pushVo.getOtherText())){
                        stringRedisTemplate.opsForHash().delete("call:other_text",pushVo.getOtherText());
                    }
                }catch (Exception e){
                    log.error("push_call_hang_up_error:"+pushVo,e);
                }

            });
        }
    }

    public CallGateway gatewayRegion(GatewayByRegionVo vo) {
        String city = phoneDat.getCity(vo.getUserPhone());
        if (StrUtil.isNotBlank(city)) {
            List<CallGateway> callGateways = callGatewayMapper.selectList(Wrappers.lambdaQuery(CallGateway.class)
                    .eq(CallGateway::getGs, city).eq(CallGateway::getCompany, vo.getCompany()).eq(CallGateway::getSyncstate, 1)
                    .eq(CallGateway::getEnablegw, 1).isNull(CallGateway::getAgentgw));
            if (CollUtil.isNotEmpty(callGateways)) {
                return RandomUtil.randomEle(callGateways);
            }
        }
        return null;
    }

    //呼入挂机时候，如有转接纪录，把转接纪录生成呼入纪录
    void handleTransfer(CallHangUpVo hangUpVo){
        List<CallTransfer> transferList = callTransferMapper.selectList(Wrappers.lambdaQuery(CallTransfer.class)
                .eq(CallTransfer::getCallId, hangUpVo.getId()));
         transferList.forEach(transfer->{
             String transferId = transfer.getUuid();
             CallStart start = callStartMapper.selectOne(Wrappers.lambdaQuery(CallStart.class)
                             .eq(CallStart::getCallId,hangUpVo.getId())
                     .eq(CallStart::getTransferId, transferId).last("limit 1"));
             if(start==null) {
                 //如果没有，插入新数据
                 CallStart insertStart = BeanUtil.toBean(transfer, CallStart.class);
                 insertStart.setTransferId(transferId);
                 insertStart.setHangupCauseTime(transfer.getCallEndTime());
                 insertStart.setIstransfer("2");
                 callStartMapper.insert(insertStart);
                 log.info("handleTransfer_insertStart:{},{}",transfer,insertStart);
             }else {
                 //如果有，更新新数据
                 CallStart updateStart = BeanUtil.toBean(transfer, CallStart.class);
                 updateStart.setOid(start.getOid());
                 updateStart.setTransferId(transferId);
                 updateStart.setHangupCauseTime(transfer.getCallEndTime());
                 updateStart.setIstransfer("2");
                 callStartMapper.updateById(updateStart);
                 log.info("handleTransfer_updateStart:{},{}",transfer,updateStart);
             }
             //回传callIn，更新其他数据
             hangUpVo.setTransferId(transferId);
             callIn(hangUpVo);
         });
    }

    public CallCompany initCallCompany(SysTenant sysTenant) {
        if (StrUtil.isBlank(sysTenant.getTenantId())) {
            throw BusinessException.msg("租户id不能为空！");
        }
        CallCompany callCompany = new CallCompany();
        callCompany.setFid(sysTenant.getTenantId());
        callCompany.setFName(sysTenant.getTenantName());
        callCompanyMapper.insert(callCompany);
        log.info("初始化呼叫租户信息:{}", JacksonUtil.toString(callCompany));
        return callCompany;
    }
}
